package com.lanou3g.zjl.chating.home.message;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.base.BaseFragment;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import butterknife.Bind;
import de.greenrobot.event.EventBus;


/**
 * Created by dllo on 15/11/17.
 */
public class MessageFragment extends BaseFragment {
    private RecyclerView messageFrg_Rv;
    private String username; // 用户名
    //    private String keyword; // 搜索框输入的字
    private InputMethodManager inputMethodManager; // 操纵输入法对象
//    private DialogFragment mMenuDialogFragment; // 菜单

    protected List<EMConversation> conversationList = new ArrayList<EMConversation>();
    private ConversationRvAdapter adapter;

    @Bind(R.id.userName_Tv)
    TextView userName_Tv;
    @Bind(R.id.msgSearch_Et)
    EditText msgSearch_Et;
    @Bind(R.id.search_Ll)
    LinearLayout search_Ll;

    @Override
    protected View getLayout(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_message, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    public void initView(View view) {
        EventBus.getDefault().register(this);
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 1);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        messageFrg_Rv = (RecyclerView) view.findViewById(R.id.messageFrg_Rv);
        messageFrg_Rv.setLayoutManager(gridLayoutManager);
        adapter = new ConversationRvAdapter(getActivity(), username);
        messageFrg_Rv.setAdapter(adapter);
        // 会话列表加载所有会话

        conversationList = loadConversationList();
        adapter.addData(conversationList);

        /**
         * 点击隐藏软键盘
         * */
        messageFrg_Rv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard();
                return false;
            }
        });

        /**
         * 搜索监听
         * */
        msgSearch_Et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null && s.length() > 0) {
                    search_Ll.setVisibility(View.GONE);
                    adapter.getFilter().filter(s);
                }

                else {
                    search_Ll.setVisibility(View.VISIBLE);
                    conversationList.clear();
                    conversationList.addAll(loadConversationList());
                    adapter.addData(conversationList);
                }
            }
        });

    }

    @Override
    protected void initData() {
        username = EMChatManager.getInstance().getCurrentUser();
//        username = getActivity().getIntent().getStringExtra("username");
        userName_Tv.setText(username);
        msgListener();
    }

    /**
     * 更改设置之后更新列表的显示
     */
    public void onEventMainThread(String isAcceptNews) {
        if (isAcceptNews != null) {
            adapter = new ConversationRvAdapter(getActivity(), username);
            messageFrg_Rv.setAdapter(adapter);
            adapter.addData(loadConversationList());
        }
    }

    public void onEventMainThread(Double a) {
        conversationList.clear();
        conversationList.addAll(loadConversationList());
        adapter = new ConversationRvAdapter(getActivity(), username);
        messageFrg_Rv.setAdapter(adapter);
        adapter.addData(conversationList);
    }


    /**
     * 获取会话列表
     *
     * @return
     */
    protected List<EMConversation> loadConversationList() {
        // 获取所有会话，包括陌生人
        Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations();

        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        // 同步
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    if (conversation.getType() != EMConversation.EMConversationType.ChatRoom) {
                        sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    }
                }
            }
        }
        try {
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }


    /**
     * 根据最后一条消息的时间排序
     * comparator类是比较用的
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
    }

    /**
     * 隐藏软键盘
     */
    protected void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

//    /**
//     * 过滤 输入的str
//     */
//    public void filter(CharSequence str) {
//        adapter.getFilter().filter(str);
//    }

    /**
     * 接收消息的监听
     */
    public void msgListener() {
        EMChatManager.getInstance().registerEventListener(
                new EMEventListener() {

                    @Override
                    public void onEvent(EMNotifierEvent event) {

                        switch (event.getEvent()) {
                            case EventNewMessage: // 接收新消息
                            {
//                                conversationList.clear();
//                                conversationList.addAll(loadConversationList());
//                                adapter.addData(loadConversationList());
                                adapter.notifyDataSetChanged();
                                break;
                            }
                            case EventDeliveryAck: {//接收已发送回执
                                break;
                            }
//
//                            case EventNewCMDMessage: {//接收透传消息
//
//                                break;
//                            }
//
                            case EventReadAck: {//接收已读回执

                                break;
                            }
//
//                            case EventOfflineMessage: {//接收离线消息
//                                List<EMMessage> messages = (List<EMMessage>) event.getData();
//                                break;
//                            }
//
//                            case EventConversationListChanged: {//通知会话列表通知event注册（在某些特殊情况，SDK去删除会话的时候会收到回调监听）
//
//                                break;
//                            }

                            default:
                                break;
                        }
                    }
                }
        );
    }

    @Override
    public void onPause() {
        super.onPause();
        msgSearch_Et.setText(null);
    }

    @Override
    public void onResume() {
        super.onResume();
        conversationList.clear();
        conversationList.addAll(loadConversationList());
        adapter.addData(loadConversationList());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
